<template>
  <div ref="chartContainer" :style="{ width: '100%', height: '100%' }"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  chartData: {
    type: Array,
    default: () => []
  }
});

const chartContainer = ref(null);
let chartInstance = null;

const initChart = () => {
  if (chartInstance) {
    chartInstance.dispose();
  }

  if (!chartContainer.value || !props.chartData.length) return;

  chartInstance = echarts.init(chartContainer.value);

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['私信数量', '账号使用']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: [
        '00:00', '01:00', '02:00', '03:00', '04:00', '05:00',
        '06:00', '07:00', '08:00', '09:00', '10:00', '11:00',
        '12:00', '13:00', '14:00', '15:00', '16:00', '17:00',
        '18:00', '19:00', '20:00', '21:00', '22:00', '23:00'
      ]
    },
    yAxis: {
      type: 'value'
    },
    series: props.chartData.map((data, index) => ({
      name: ['私信数量', '账号使用'][index],
      type: 'line',
      smooth: true,
      data
    }))
  };

  chartInstance.setOption(option);
};

onMounted(() => {
  initChart();
  const resizeHandler = () => chartInstance && chartInstance.resize();
  window.addEventListener('resize', resizeHandler);

  onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeHandler);
    if (chartInstance) {
      chartInstance.dispose();
    }
  });
});

watch(() => props.chartData, (newData) => {
  if (newData && newData.length > 0) {
    initChart();
  }
});
</script>

<style scoped>
</style>
